package com.mlick.a.csnotes;

import java.util.concurrent.Semaphore;

/**
 * @author lixiangxin
 * @date 2019/3/15 23:21
 *
 *通过N个线程顺序循环打印从0至100，如给定N=3则输出:
 * thread0: 0
 * thread1: 1
 * thread2: 2
 * thread0: 3
 * thread1: 4
 * .....
 **/
public class T2  {

    private static final int N = 3;
    private static int result = 0;

    public static void main(String[] args) throws InterruptedException {

        final Semaphore[] semaphores = new Semaphore[N];
        for (int i = 0; i < N; i++) {
            semaphores[i] = new Semaphore(1);
            if (i != N-1){
                semaphores[i].acquire();
            }
        }
        for (int i = 0; i < N; i++) {
            final Semaphore lastSemaphore = i==0? semaphores[N-1]:semaphores[i-1];
            final Semaphore curSemaphore = semaphores[i];

            new Thread(new Runnable() {
                public void run() {
                    while (true){
                        try {
                            lastSemaphore.acquire();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }

                        System.out.println(Thread.currentThread().getName()+"=>"+result++);

                        if (result > 100){
                            System.exit(0);
                        }
                        curSemaphore.release();
                    }
                }
            }).start();
        }
    }
}
